import os
import time
from datetime import datetime
from docx import Document
from docx.shared import Pt, Cm, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_TAB_ALIGNMENT
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.section import WD_ORIENTATION
from docx.oxml.ns import qn
import win32print
import win32api


class HealthCheckPrinter:
    """体检单打印类"""
    
    def __init__(self):
        self.default_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'reports')
        # 确保输出文件夹存在
        if not os.path.exists(self.default_folder):
            os.makedirs(self.default_folder)
    
    def get_default_printer(self):
        """获取默认打印机名称"""
        try:
            return win32print.GetDefaultPrinter()
        except Exception as e:
            print(f"获取默认打印机失败: {e}")
            return None
    
    def get_available_printers(self):
        """获取可用打印机列表"""
        printers = []
        try:
            for printer in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 1):
                printers.append(printer[2])
            return printers
        except Exception as e:
            print(f"获取打印机列表失败: {e}")
            return []
    
    def generate_report(self, patient_info, package, save_path=None):
        """生成体检报告Word文档"""
        if not patient_info:
            print("错误: 缺少患者信息")
            return None
        
        if not package or not package.items:
            print("错误: 体检套餐为空或没有项目")
            return None
        
        # 如果没有指定保存路径，则使用默认路径
        if not save_path:
            filename = f"{patient_info.get('姓名', '未知')}_体检报告_{time.strftime('%Y%m%d%H%M%S')}.docx"
            save_path = os.path.join(self.default_folder, filename)
        
        # 创建Word文档
        doc = Document()
        
        # 设置页面为横向
        section = doc.sections[0]
        section.orientation = WD_ORIENTATION.LANDSCAPE
        section.page_width, section.page_height = section.page_height, section.page_width  # 交换宽高
        
        # 设置页边距（单位：厘米）
        section.left_margin = Cm(2)
        section.right_margin = Cm(2)
        section.top_margin = Cm(2)
        section.bottom_margin = Cm(2)
        
        # 标题
        title = doc.add_heading('重庆润之康医院体检指引单', level=0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        # 设置标题格式
        title_run = title.runs[0]
        title_run.font.name = '宋体'
        title_run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
        title_run.font.size = Pt(16)
        title_run.font.bold = True
        
        # 添加患者信息表格
        info_table = doc.add_table(rows=3, cols=2)
        info_table.style = 'Table Grid'
        info_table.autofit = False
        
        # 设置列宽
        info_table.columns[0].width = Cm(8)  # 左侧列
        info_table.columns[1].width = Cm(8)  # 右侧列
        
        # 填充患者信息表格
        info_texts = [
            # 第一行
            (info_table.rows[0].cells[0], f"姓    名：{patient_info.get('姓名', '')}", WD_ALIGN_PARAGRAPH.LEFT),
            (info_table.rows[0].cells[1], f"单    位：{patient_info.get('单位', '个人体检三项')}", WD_ALIGN_PARAGRAPH.LEFT),
            # 第二行
            (info_table.rows[1].cells[0], f"性    别：{patient_info.get('性别', '')}", WD_ALIGN_PARAGRAPH.LEFT),
            (info_table.rows[1].cells[1], f"电    话：", WD_ALIGN_PARAGRAPH.LEFT),
            # 第三行
            (info_table.rows[2].cells[0], f"年    龄：{patient_info.get('年龄', '')}", WD_ALIGN_PARAGRAPH.LEFT),
            (info_table.rows[2].cells[1], f"身份证号：{patient_info.get('身份证号', '')}", WD_ALIGN_PARAGRAPH.LEFT),
        ]
        
        # 统一设置信息表格字体
        for cell, text, alignment in info_texts:
            paragraph = cell.paragraphs[0]
            paragraph.alignment = alignment
            run = paragraph.add_run(text)
            run.font.name = '宋体'
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
            run.font.size = Pt(12)
        
        doc.add_paragraph()  # 添加空行
        
        # 添加体检项目表格
        items_table = doc.add_table(rows=len(package.items)+1, cols=2)
        items_table.style = 'Table Grid'
        items_table.alignment = WD_TABLE_ALIGNMENT.CENTER
        
        # 设置表格列宽
        items_table.autofit = False
        items_table.columns[0].width = Cm(8)  # 项目名称列
        items_table.columns[1].width = Cm(4)  # 状态列
        
        # 表头
        header_cells = items_table.rows[0].cells
        header_texts = [
            (header_cells[0], "项目名称"),
            (header_cells[1], "状态")
        ]
        
        # 设置表头样式
        for cell, text in header_texts:
            paragraph = cell.paragraphs[0]
            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
            run = paragraph.add_run(text)
            run.font.name = '宋体'
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
            run.font.size = Pt(12)
            run.font.bold = True
        
        # 填充体检项目
        for i, item in enumerate(package.items, 1):
            row_cells = items_table.rows[i].cells
            cell_texts = [
                (row_cells[0], item.name, WD_ALIGN_PARAGRAPH.LEFT),
                (row_cells[1], "□", WD_ALIGN_PARAGRAPH.CENTER)
            ]
            
            for cell, text, alignment in cell_texts:
                paragraph = cell.paragraphs[0]
                paragraph.alignment = alignment
                run = paragraph.add_run(text)
                run.font.name = '宋体'
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
                run.font.size = Pt(12)
        
        # 添加页脚信息
        footer = doc.sections[0].footer
        footer_para = footer.paragraphs[0]
        footer_text = f"打印时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        footer_para.text = ""  # 清除原有文本
        run = footer_para.add_run(footer_text)
        run.font.name = '宋体'
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
        run.font.size = Pt(10)
        footer_para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
        
        # 保存文档
        try:
            doc.save(save_path)
            print(f"体检报告已保存至: {save_path}")
            return save_path
        except Exception as e:
            print(f"保存文档失败: {e}")
            return None
    
    def print_report(self, file_path, printer_name=None):
        """打印体检报告"""
        if not os.path.exists(file_path):
            print(f"错误: 文件不存在 {file_path}")
            return False
        
        # 如果没有指定打印机，则使用默认打印机
        if not printer_name:
            printer_name = self.get_default_printer()
            if not printer_name:
                print("错误: 未找到默认打印机")
                return False
        
        try:
            # 使用Word应用程序打印文档
            win32api.ShellExecute(
                0, 
                "print", 
                file_path,
                f"/d:\"{printer_name}\"", 
                ".", 
                0
            )
            print(f"文档已发送到打印机: {printer_name}")
            return True
        except Exception as e:
            print(f"打印文档失败: {e}")
            return False
    
    def print_preview(self, file_path):
        """打开Word文档进行打印预览"""
        if not os.path.exists(file_path):
            print(f"错误: 文件不存在 {file_path}")
            return False
        
        try:
            # 使用默认应用程序打开文档
            os.startfile(file_path)
            print(f"已打开文档: {file_path}")
            return True
        except Exception as e:
            print(f"打开文档失败: {e}")
            return False 